package com.example.blog.controller;

import com.example.blog.entity.Article;
import com.example.blog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章控制器类，处理文章相关的HTTP请求
 * 提供文章的增删改查API接口
 */
@RestController
@RequestMapping("/api/posts")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 创建新文章
     * @param article 文章信息对象，包含标题、内容和作者ID
     * @return 创建成功的文章对象
     */
    @PostMapping
    public ResponseEntity<Article> createArticle(@Valid @RequestBody Article article) {
        // 记录请求信息
        System.out.println("收到创建文章请求，标题：" + article.getTitle() + "，作者ID：" + article.getUserId());
        
        // 调用服务层创建文章
        Article createdArticle = articleService.createArticle(article);
        
        // 返回创建成功的文章和201状态码
        return new ResponseEntity<>(createdArticle, HttpStatus.CREATED);
    }

    /**
     * 获取所有文章列表
     * @return 文章列表，按创建时间降序排列
     */
    @GetMapping
    public ResponseEntity<List<Article>> getAllArticles() {
        List<Article> articles = articleService.getAllArticles();
        return ResponseEntity.ok(articles);
    }

    /**
     * 根据ID获取文章详情
     * @param id 文章ID
     * @return 文章详细信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getArticleById(@PathVariable Long id) {
        Article article = articleService.getArticleById(id);
        if (article == null) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "文章不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
        return ResponseEntity.ok(article);
    }

    /**
     * 更新文章信息
     * @param id 文章ID
     * @param article 更新后的文章信息
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateArticle(@PathVariable Long id, @Valid @RequestBody Article article) {
        // 设置文章ID
        article.setId(id);
        
        // 调用服务层更新文章
        boolean updated = articleService.updateArticle(article);
        
        if (updated) {
            return ResponseEntity.ok(article);
        } else {
            Map<String, String> response = new HashMap<>();
            response.put("message", "文章更新失败，可能是文章不存在或您没有权限");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
    }

    /**
     * 删除文章
     * @param id 文章ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteArticle(@PathVariable Long id) {
        boolean deleted = articleService.deleteArticle(id);
        
        if (deleted) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "文章删除成功");
            return ResponseEntity.ok(response);
        } else {
            Map<String, String> response = new HashMap<>();
            response.put("message", "文章删除失败，可能是文章不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
    }

    /**
     * 获取指定用户的所有文章
     * @param userId 用户ID
     * @return 该用户发布的文章列表
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Article>> getArticlesByUserId(@PathVariable Long userId) {
        List<Article> articles = articleService.getArticlesByUserId(userId);
        return ResponseEntity.ok(articles);
    }
}